package com.wd.good.proxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @description: cglib动态代理，不需要实现接口的类也可以使用
 * @author wangdpng
 * @date 2023/11/18 19:16
 */
@Component
public class CglibRetryProxyHandler implements MethodInterceptor {

    private Object subject;


    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        int times = 1;
        while (times <= 5) {
            try{
                int i = 3/0;
                method.invoke(subject,args);
            }catch (RuntimeException e){
                System.out.println("调用动态代理，重试次数"+ times +"次");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException ex) {
                    throw new RuntimeException(ex);
                }
                times++;
                if (times > 5) {
                    throw new RuntimeException("重试次数超过5次");
                }
            }
        }
        return null;
    }

    public Object getCglibProxy(Object subject){
        this.subject = subject;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(subject.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }
}
